package com.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gulimall.product.vo.Catelog2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.product.dao.CategoryDao;
import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationServiceImpl categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //组装父子树结构
        List<CategoryEntity> parent = entities.stream()
                .filter( entity ->  entity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
                })
                .sorted((menu1,menu2) -> { return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0: menu2.getSort());})
                .collect(Collectors.toList());
        return parent;
    }

    @Override
    public void removeMenuByIds(List<Long> ids) {
        //TODO 1.检查当前删除的菜单，是否被被的地方调用

        //逻辑删除
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        paths = findParentPath(catelogId,paths);
//        Collections.reverse(paths);
        return  paths.toArray(new Long[paths.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0).eq("show_status", 1));
        return list;
    }

    @Override
    public Map<String, List<Catelog2VO>> getCatalogJson() {

        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)){
            Map<String, List<Catelog2VO>> catalogJsonFromDB = getCatalogJsonFromDB();
            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(catalogJsonFromDB));
            return catalogJsonFromDB;
        }
        Map<String, List<Catelog2VO>> result = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2VO>>>(){});
        return result;
    }

    public Map<String, List<Catelog2VO>> getCatalogJsonFromDB() {


        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //一級
//        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);

        Map<String, List<Catelog2VO>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> entities = getParent_cid(selectList,v.getCatId());
//            baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", parentId));
            //封装上面的
            List<Catelog2VO> catelog2 = null;
            if (entities != null) {
                catelog2 = entities.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> category3List = getParent_cid(selectList,l2.getCatId());
//                    baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (category3List != null) {
                        List<Catelog2VO.Catelog3VO> catelog3VOList = category3List.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                        catelog2VO.setCatalog3List(catelog3VOList);
                    }

                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2;
        }));
        return collect;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentId) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parentId).collect(Collectors.toList());
        return collect;
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", parentId));
    }

    public List<Long> findParentPath(Long catelogId ,List<Long> path){
        path.add(0,catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),path);
        }
        return path;
    }

    //递归找所有菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root ,List<CategoryEntity> all){
        return all.stream()
                .filter( entity -> entity.getParentCid() == root.getCatId())
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu,all));
                    return menu;
                })
                .sorted((menu1,menu2) -> { return (menu1.getSort() == null ? 0:menu1.getSort()) - (menu2.getSort() == null ? 0: menu2.getSort());})
                .collect(Collectors.toList());
    }

}